<%@ page language="java" contentType="text/html; charset=UTF-8"	 pageEncoding="UTF-8"%>
<%@ include file="../include/laypublic.jsp"%>
<!DOCTYPE html>
<html>
<head>
  <title>角色管理</title>
  <!-- <style type="text/css">
  .layui-tree-iconArrow { opacity: 0;visibility: hidden;diaplay: none;position: absolute; }
  .layui-tree-iconClick { pointer-events: none; }
  </style> -->
</head>
<body>
  <div class="layui-fluid">   
    <div class="layui-card">
      <div id="query-form" class="layui-form layui-card-header layuiadmin-card-header-auto">
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label">角色名称</label>
            <div class="layui-input-inline">
              <input type="text" name="sroleName" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
          </div>
          <shiro:hasPermission name="LIST_ROLE">
          <div class="layui-inline">
            <button class="layui-btn layuiadmin-btn-admin" lay-submit lay-filter="LAY-user-role-search">
              <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>查询
            </button>
            <button class="layui-btn layuiadmin-btn-admin" lay-submit lay-filter="LAY-user-back-reset">
              <i class="layui-icon layui-icon-fonts-clear  layuiadmin-button-btn"></i>重置
            </button>
          </div>
          </shiro:hasPermission>
        </div>
      </div>
  
      <div class="layui-card-body">
         <shiro:hasPermission name="ADD_ROLE">
        	<div style="padding-bottom: 10px;">
	          	<button class="layui-btn layuiadmin-btn-admin " data-type="add">
	          	 <i class="layui-icon layui-icon-add-1 layuiadmin-button-btn"></i>新增
	          	</button>
        	</div>
         </shiro:hasPermission>
        
        <table id="LAY-user-role-manage" lay-filter="LAY-user-role-manage"></table>
        
        <div class="layui-form" lay-filter="add_form" id="add_form" style="padding: 20px 30px 0 0;display:none">
		    <div class="layui-form-item">
		      <label class="layui-form-label">角色名称</label>
		      <div class="layui-input-inline">
		        <input type="text" name="sroleName" maxlength="50" lay-verify="required" placeholder="请输入角色名称" autocomplete="off" class="layui-input">
		      </div>
		    </div>
		    <div class="layui-form-item layui-form-text">
			    <label class="layui-form-label">备注</label>
			    <div class="layui-input-block">
			      <textarea name="sremark" maxlength="100" lay-verify="required" placeholder="请输入内容" class="layui-textarea"></textarea>
			    </div>
		  	</div>
		    <div class="layui-form-item layui-hide">
		      <input type="button" lay-submit lay-filter="add_form_submit" id="add_form_submit" value="确认">
		    </div>
	  	</div>
	  	
        <div class="layui-form" lay-filter="edit_form" id="edit_form" style="padding: 20px 30px 0 0;display:none">
        	<input type="hidden" name="id" />
		    <div class="layui-form-item">
		      <label class="layui-form-label">角色名称</label>
		      <div class="layui-input-inline">
		        <input type="text" name="sroleName" maxlength="50" lay-verify="required" placeholder="请输入角色名称" autocomplete="off" class="layui-input">
		      </div>
		    </div>
		    <div class="layui-form-item layui-form-text">
			    <label class="layui-form-label">备注</label>
			    <div class="layui-input-block">
			      <textarea name="sremark" maxlength="100" lay-verify="required" placeholder="请输入内容" class="layui-textarea"></textarea>
			    </div>
		  	</div>
		    <div class="layui-form-item layui-hide">
		      <input type="button" lay-submit lay-filter="edit_form_submit" id="edit_form_submit" value="确认">
		    </div>
	  	</div>
	  	
       	<!-- 分配角色div  -->
       	<div id="w_givenpurview" lay-filter="w_givenpurview" class="layui-form" style="padding: 10px 30px 0 0;display:none">
         	<input type="hidden" name="roleId" />
			<input type="hidden" name="checkPurviewId" />
			<input type="hidden" name="clickMenuIds" id="clickMenuIds" value=''/>
			<!-- <div style="color:red;margin-left:40px;">※ <B>修改时：</B>“单击”已分配权限的某个菜单，勾选新的权限 ※</div>
         	 -->
         	 <div id="purviewTree" style="margin-left:31px"></div>
         	<div class="layui-form-item layui-hide">
                <input type="button" lay-submit id="lay-given-role-submit" lay-filter="lay-given-role-submit" value="确认修改"/>
            </div>
        </div>
      </div>
    </div>
  </div>

  <script>
  layui.config({
    base: '${ctx}/resources/layuiadmin/' //静态资源所在路径
  }).extend({
    index: 'lib/index' //主入口模块
  }).use(['index', 'table', 'set', 'tree'], function(){
    var $ = layui.$
    ,form = layui.form
    ,table = layui.table;

    //角色管理
    table.render({
      elem: '#LAY-user-role-manage'
      ,url: basePath + '/role/queryData' //请求数据接口
      ,cols: [[
        {type: 'checkbox', fixed: 'left'}
        ,{field: 'sroleCode', title: '角色编号'}
        ,{field: 'sroleName', title: '角色名称'}
        ,{field: 'sremark', title: '备注'}
        ,{title: '操作', width: 350, align:'center', fixed: 'right', templet: function(d){
	      	  var optStr ="";
	      	  <shiro:hasPermission name="EDIT_ROLE">
		      	  if(d.sroleCode == 's_r000001'){
			     	 if('${loginUserName}' == 'admin'){
			      	  	optStr += '<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
			      	 }else{
		      			optStr += '<a class="layui-btn layui-btn-disabled layui-btn-xs"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
			      	 }
		         }else{
		      	  	optStr += '<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
		    	 }	 
	  	  	  </shiro:hasPermission>
	  	  	  <shiro:hasPermission name="DELETE_ROLE">
		  	  	 if(d.sroleCode == 's_r000001'||d.sroleCode == 's_r000002'){
		    		 optStr += '<a class="layui-btn layui-btn-disabled layui-btn-xs"><i class="layui-icon layui-icon-delete"></i>删除</a>';
		    	 }else{
		    		 optStr += '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';
		    	 }	
	  		  </shiro:hasPermission>
	  		  <shiro:hasPermission name="ASSIGN_ROLE">
	  		     if(d.sroleCode == 's_r000001'){
			         if('${loginUserName}' == 'admin'){
			  			 optStr += '<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="givenPurview"><i class="layui-icon layui-icon-auz"></i>分配权限</a>';
			      	 }else{
			  			 //optStr += '<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="givenPurview"><i class="layui-icon layui-icon-auz"></i>分配权限</a>';
			  			 optStr += '<a class="layui-btn layui-btn-disabled layui-btn-xs" ><i class="layui-icon layui-icon-auz"></i>分配权限</a>';
			      	 }
		    	 }else{
		  			 optStr += '<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="givenPurview"><i class="layui-icon layui-icon-auz"></i>分配权限</a>';
		    	 }	
	  		  </shiro:hasPermission>
	  		  return optStr;
        	}
        }
      ]]
      ,page: true
      ,limit: 10
    });
    
    <shiro:hasPermission name="LIST_ROLE">
    //监听搜索
    form.on('submit(LAY-user-role-search)', function(data){
      //执行重载
      table.reload('LAY-user-role-manage', {page: {curr: 1},
        where: trimData(data)
      });
    });
 	//重置清空
    form.on('submit(LAY-user-back-reset)', function(data){
    	reset_form('query-form');
    });
    </shiro:hasPermission>
  
    //监听工具条
    table.on('tool(LAY-user-role-manage)', function(obj){
      var data = obj.data;
      if(obj.event === 'del'){
          layer.confirm('确定删除？',{icon:3, title :'提示'}, function(index){
          	$.ajax({
  				type : 'post',
  				url : basePath + '/role/delete?checkboxId=' + data.id,
  				success:function(result){
  					if(result.success){
  						table.reload('LAY-user-role-manage'); //数据刷新
  						layer.close(index);
  					}else{
  						layer.msg(result.msg,{icon: 7});
  				  	}
  				}
  			});
          });
      } else if(obj.event === 'edit'){
      	form.val('edit_form',data);
      	layer.open({
            type: 1
            ,title: '编辑角色'
            ,content: $('#edit_form')
            ,area: layui.admin.screen() < 2 ? ['80%', '300px'] : ['420px','300px']
            ,btn: ['确定', '取消']
            ,btnAlign: 'c'
            ,yes: function(index, layero){
          	  var submitID = 'edit_form_submit'
          		  ,submit = layero.contents().find('#'+ submitID);
          	  //监听提交
          	  form.on('submit('+ submitID +')', function(data){
                var field = data.field; //获取提交的字段
                //提交 Ajax 成功后，静态更新表格中的数据
                $.ajax({
                    type : 'post',
  					url : basePath + '/role/save',
                    data: field,
  					success:function(result){
  						if(result.success){
                			table.reload('LAY-user-role-manage'); //数据刷新
                			layer.close(index); //关闭弹层
  						}else{
  							layer.msg(result.msg,{icon: 7});
  					  	}
  					}
                });
              });  
              submit.trigger('click');
            }
          });
        }else if(obj.event === 'givenPurview'){//分配权限
        	layer.load();
            setTimeout(function(){layer.closeAll('loading');}, 4000);
       	  	var tree = layui.tree;
       	 	$("input[name=roleId]").val(data.id);
       	 	var treeData = [];
  	  	  	$.getJSON('${ctx}/role/getLayTree?roleId='+data.id, function (data) {
  		    	if(data != null && data.length > 0){
  		    		treeData = data;
  		    	}
			 	//渲染权限树
       	    	tree.render({
       	      		elem: '#purviewTree'  //绑定元素
       	      		,data: treeData
		       	    ,id: 'treeRender' //定义索引
		       	    ,showCheckbox:true	//是否显示复选框
       	      		,onlyIconControl: false  //是否仅允许节点左侧图标控制展开收缩
       	      		,showLine:true	//是否开启连接线。默认 true，若设为 false，则节点左侧出现三角图标。
	       	      	,click: function(obj){
	       	         	// 最后一级，打开时异步加载下属选中的权限
	       	         	if(obj.data.lastStep && obj.state=='open'){
		   	      		 	layer.load(2);
			           	 	$.ajax({
			                  	type : 'post',
			   					url : basePath + '/role/getAsynLayTreeChecked?roleId='+$("input[name=roleId]").val()+'&clickMenuId='+obj.data.id,
			   					success:function(result){
			   						if(result.success){
				               	 		var checkedArr = [];
				               	 		layui.$.each(result.entity, function(i,item){
				               	 			checkedArr.push(item.spurviewId);   
				   				        });
				               	 		tree.setChecked('treeRender', checkedArr);
				                  		layer.closeAll('loading');
				                  		$('#clickMenuIds').val($('#clickMenuIds').val()+','+obj.data.id);// 添加到clickMenuIds
			   						}else{
				                  		layer.closeAll('loading');
			   							layer.msg("加载已分配权限失败，请重试~",{icon: 7});
			   					  	}
			   					}
			              	});
		        		}
	       	       }
       	    	   ,oncheck: function(obj){
	       	         	// 最后一级，异步加载下属选中的权限
	       	         	if(obj.data.lastStep && obj.checked){
		   	      		 	layer.load(2);
			           	 	$.ajax({
			                  	type : 'post',
			   					url : basePath + '/role/getAsynLayTreeChecked?roleId='+$("input[name=roleId]").val()+'&clickMenuId='+obj.data.id,
			   					success:function(result){
			   						if(result.success){
				               	 		var checkedArr = [];
				               	 		layui.$.each(result.entity, function(i,item){
				               	 			checkedArr.push(item.spurviewId);   
				   				        });
				               	 		tree.setChecked('treeRender', checkedArr);
				                  		layer.closeAll('loading');
				                  		$('#clickMenuIds').val($('#clickMenuIds').val()+','+obj.data.id);// 添加到clickMenuIds
			   						}else{
				                  		layer.closeAll('loading');
			   							layer.msg("加载已分配权限失败，请重试~",{icon: 7});
			   					  	}
			   					}
			              	});
		        		}
	       	       }
       	   	   });
  	  	}).success(function(){
	  	  layer.open({
         	 title: '角色<' + obj.data.sroleName + '>分配权限'
             ,type: 1
             ,shadeClose: false
             ,btn: ['确定', '取消']
             ,btnAlign: 'c'
             ,area: layui.admin.screen() < 2 ? ['80%', '550px'] : ['500px', '550px']
             ,content: $('#w_givenpurview')
             ,success: function(layero, index){
              	$('#clickMenuIds').val(''); 	 
           	  }
             ,yes: function(index, layero){
              layer.load();		 
           	  var submitID = 'lay-given-role-submit'
           		  ,submit = layero.contents().find('#'+ submitID);
           		//获得选中的节点
           	  var treeRenderData = tree.getChecked('treeRender');
              var dataArray = new Array();
           	  for(var ind in treeRenderData){
           		  var checkData = treeRenderData[ind].children;
              	  for(var i in checkData){
              		  var trData = checkData[i];
              		  for(var j in trData.children){
              			  var purData = trData.children[j];
              			  if(purData.children.length > 0){
              				  for(var k in purData.children){
                			  	var purviewData = purData.children[k];
               		  		  	dataArray.push(purviewData.id);
                		  	  }
              			  }else{
             		  		  dataArray.push(purData.id);
              			  }
              		  }
              	  }
           	  }
           	  $("input[name=checkPurviewId]").val(dataArray);             	  	
           	  	  //分配权限提交
 		    	  form.on('submit('+ submitID +')', function(data){
	  		    	$.post(basePath + '/role/saveRolePurview', data.field, function(result) {
	  		    		if (result.success) {
	  		    			layer.closeAll('loading');
	  		    			layer.msg('分配权限成功~',{icon: 1});
	  						layer.close(index);
	  						clean_form("w_givenpurview");//清空表单
	  					}else{
	  		    			layer.closeAll('loading');
	  						layer.msg(result.msg,{icon: 7});
	  					}
	  				});
	  		    });
 		    	submit.trigger('click');
             }
           });
	  	 })
        }
    });
    
    
    /* $('#purviewTree').on('click','.layui-tree-iconArrow',function(event){
    	event.preventDefault();
    	})
     $('#purviewTree').on('click','.layui-tree-iconClick',function(event){
    	event.preventDefault();
    	})	
    	
    	 $('#purviewTree').on('click','.layui-tree-main',function(event){
    	event.preventDefault();
    	})	 */
    	
    
    //新增按钮事件
    var active = {
      add: function(){
        layer.open({
          type: 1
          ,title: '添加角色'
          ,content: $('#add_form')
          ,area: layui.admin.screen() < 2 ? ['80%', '300px'] : ['420px','300px']
          ,btn: ['确定', '取消']
          ,btnAlign: 'c'
          ,yes: function(index, layero){
        	  var submitID = 'add_form_submit'
            	,submit = layero.contents().find('#'+ submitID);

              //监听提交
           	  form.on('submit('+ submitID +')', function(data){
              	var field = data.field; //获取提交的字段
              	//提交 Ajax 成功后，静态更新表格中的数据
              	$.ajax({
                  	type : 'post',
					url : basePath + '/role/save',
                  	data: field,
					success:function(result){
						if(result.success){
              				table.reload('LAY-user-role-manage'); //数据刷新
              				layer.close(index); //关闭弹层
              				clean_form("add_form");//清空表单
						}else{
							layer.msg(result.msg,{icon: 7});
					  	}
					}
              	});
            });  
            submit.trigger('click');
          }
        }); 
      }
    }  
    $('.layui-btn.layuiadmin-btn-admin').on('click', function(){
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });
  });
  </script>
</body>
</html>

